package com.huike.report.service.impl;

import com.huike.clues.mapper.SysDeptMapper;
import com.huike.clues.mapper.SysUserMapper;
import com.huike.common.core.controller.BaseController;
import com.huike.common.core.domain.entity.SysDept;
import com.huike.common.core.domain.entity.SysUser;
import com.huike.common.core.page.TableDataInfo;
import com.huike.common.utils.SecurityUtils;
import com.huike.report.domain.vo.*;
import com.huike.report.mapper.ReportMapper;
import org.springframework.stereotype.Service;
import com.huike.clues.domain.TbActivity;
import com.huike.clues.domain.TbClue;
import com.huike.clues.mapper.TbActivityMapper;
import com.huike.clues.mapper.TbClueMapper;
import com.huike.contract.domain.TbContract;
import com.huike.contract.mapper.TbContractMapper;
import com.huike.report.domain.vo.ActivityStatisticsVo;
import com.huike.report.service.IReportService;
import org.springframework.beans.BeanUtils;
import com.huike.report.domain.vo.TigerDragonDTO;


import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

import java.util.stream.Collectors;

/**
 * @author STJ12138
 * @version 1.0
 * @description: TODO
 * @date 2023/7/13 9:22
 */
@Service
public class ReportServiceImpl extends BaseController implements IReportService {
    @Resource
    private ReportMapper reportMapper;
    @Resource
    private TbActivityMapper tbActivityMapper;
    @Resource
    private TbClueMapper tbClueMapper;
    @Resource
    private TbContractMapper tbContractMapper;


    @Resource
    private SysUserMapper userMapper;

    @Resource
    private SysDeptMapper deptMapper;

    /**
     * @param beginCreateTime
     * @param endCreateTime
     * @description: 客户统计新增客户数报表
     * @param: beginCreateTime
     * endCreateTime
     * @return: com.huike.report.domain.vo.LineChartVo
     * @author STJ12138
     * @date: 2023/7/13 9:29
     */

    @Override
    public LineChartVo contractStatisticsChart(String beginCreateTime, String endCreateTime) {
        LineChartVo chartVo = new LineChartVo();
        List<LocalDate> localDates = getLocalDates(beginCreateTime, endCreateTime);
        //获取到每天的时间
        ArrayList<Object> doubles1 = new ArrayList<>(); //每天新增
        ArrayList<Object> doubles2 = new ArrayList<>(); //总量
        localDates.forEach(localDate -> {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Double sum1 = reportMapper.contractStatisticsChart(beginTime, endTime);
            sum1 = sum1 == null ? 0 : sum1;
            doubles1.add(sum1);
            Double sum2 = reportMapper.contractStatisticsChart(null, endTime);
            sum2 = sum2 == null ? 0 : sum2;
            doubles2.add(sum2);
        });
        LineSeriesVo lineSeriesVo1 = new LineSeriesVo();
        lineSeriesVo1.setName("新增客户数");
        lineSeriesVo1.setData(doubles1);
        LineSeriesVo lineSeriesVo2 = new LineSeriesVo();
        lineSeriesVo2.setName("客户总数");
        lineSeriesVo2.setData(doubles2);

        List<LineSeriesVo> series = new ArrayList<>();
        series.add(lineSeriesVo1);
        series.add(lineSeriesVo2);
        chartVo.setSeries(series);
        List<String> xAxis = localDates.stream().map(LocalDate::toString).collect(Collectors.toList());
        chartVo.setxAxis(xAxis);

        return chartVo;
    }

    /**
     * @description: 销售统计归属部门明细列表
     * @param: beginCreateTime
     * endCreateTime
     * @return: com.huike.common.core.page.TableDataInfo<java.util.List < com.huike.report.domain.vo.ReportSalesDeptStatisticsListDataVo>>
     * @author STJ12138
     * @date: 2023/7/13 16:08
     */
    @Override
    public TableDataInfo<List<ReportSalesDeptStatisticsListDataVo>> deptStatisticsList(String beginCreateTime, String endCreateTime) {
        startPage();
        LocalDateTime begin = LocalDateTime.of(LocalDate.parse(beginCreateTime), LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(LocalDate.parse(endCreateTime), LocalTime.MAX);
        List<ReportSalesDeptStatisticsListDataVo> list = reportMapper.deptStatisticsList(begin, end);

        return getDataTable(list);
    }

    /**
     * @description: 销售统计归属人报表
     * @param: beginCreateTime
     * endCreateTime
     * @return: com.huike.common.core.page.TableDataInfo<java.util.List < com.huike.report.domain.vo.ReportSalesOwnerShipStatisticsListDataVo>>
     * @author STJ12138
     * @date: 2023/7/13 16:08
     */
    @Override
    public TableDataInfo<List<ReportSalesOwnerShipStatisticsListDataVo>> ownerShipStatisticsList(String beginCreateTime, String endCreateTime) {
        startPage();
        LocalDateTime begin = LocalDateTime.of(LocalDate.parse(beginCreateTime), LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(LocalDate.parse(endCreateTime), LocalTime.MAX);
        List<ReportSalesOwnerShipStatisticsListDataVo> list = reportMapper.ownerShipStatisticsList(begin, end);
        return getDataTable(list);
    }

    /**
     * @param beginCreateTime
     * @param endCreateTime
     * @description: 销售统计报表
     * @param: beginCreateTime
     * endCreateTime
     * @return: com.huike.report.domain.vo.LineChartVo
     * @author STJ12138
     * @date: 2023/7/13 17:12
     */
    @Override
    public LineChartVo salesStatistics(String beginCreateTime, String endCreateTime) {
        LineChartVo chartVo = new LineChartVo();
        List<LocalDate> localDates = getLocalDates(beginCreateTime, endCreateTime);
        ArrayList<Object> doubles = new ArrayList<>();
        localDates.forEach(localDate -> {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Double sum = reportMapper.salesStatistics(beginTime, endTime);
            sum = sum == null ? 0 : sum;
            doubles.add(sum);
        });
        LineSeriesVo lineSeriesVo = new LineSeriesVo();
        lineSeriesVo.setName("销售金额");
        lineSeriesVo.setData(doubles);
        List<LineSeriesVo> series = new ArrayList<>();
        series.add(lineSeriesVo);
        chartVo.setSeries(series);
        List<String> xAxis = localDates.stream().map(LocalDate::toString).collect(Collectors.toList());
        chartVo.setxAxis(xAxis);
        return chartVo;
    }

    /**
     * @param beginCreateTime
     * @param endCreateTime
     * @description: 客户统计学科分布统计报表
     * @param: beginCreateTime
     * endCreateTime
     * @return: java.util.List<com.huike.report.domain.vo.ReportSubjectStatisticsDataVo>
     * @author STJ12138
     * @date: 2023/7/13 17:33
     */
    @Override
    public List<ReportSubjectStatisticsDataVo> subjectStatistics(String beginCreateTime, String endCreateTime) {
        LocalDateTime begin = LocalDateTime.of(LocalDate.parse(beginCreateTime), LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(LocalDate.parse(endCreateTime), LocalTime.MAX);
        List<ReportSubjectStatisticsDataVo> list = reportMapper.subjectStatistics(begin, end);
        return list;
    }

    /**
     * @param beginCreateTime
     * @param endCreateTime
     * @description: 线索统计线索转换率报表
     * @param: beginCreateTime
     * endCreateTime
     * @return: com.huike.report.domain.vo.VulnerabilityMapVo
     * @author STJ12138
     * @date: 2023/7/13 18:58
     */
    @Override
    public VulnerabilityMapVo getVulnerabilityMap(String beginCreateTime, String endCreateTime) {
        LocalDateTime begin = LocalDateTime.of(LocalDate.parse(beginCreateTime), LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(LocalDate.parse(endCreateTime), LocalTime.MAX);
        //查询到所有线索
        Integer cluesNums = reportMapper.getcluesNums(begin, end);
        //查询有效线索（status != 4 || status != 5）
        Integer effectiveCluesNums = reportMapper.geteffectiveCluesNums(begin, end);
        //查询转换成商机的线索（status=6）
        Integer businessNums = reportMapper.getbusinessNums(begin, end);
        //查询转换成客户的线索（status = 7）
        Integer contractNums = reportMapper.getcontractNums(begin, end);
        VulnerabilityMapVo vulnerabilityMapVo = new VulnerabilityMapVo();
        vulnerabilityMapVo.setCluesNums(cluesNums);
        vulnerabilityMapVo.setEffectiveCluesNums(effectiveCluesNums);
        vulnerabilityMapVo.setBusinessNums(businessNums);
        vulnerabilityMapVo.setContractNums(contractNums);
        return vulnerabilityMapVo;
    }

    private List<LocalDate> getLocalDates(String begin, String end) {
        //定义日期列表
        List<LocalDate> localDates = new ArrayList<>();
        //将开始时间加入列表
        LocalDate beg = LocalDate.parse(begin);
        LocalDate e = LocalDate.parse(end);
        localDates.add(beg);
        while (!beg.equals(e)) {
            beg = beg.plusDays(1);
            localDates.add(beg);
        }
        return localDates;
    }


    /**
     * 渠道统计活动明细列表
     *
     * @param tbActivity
     * @return
     */
    @Override
    public List<ActivityStatisticsVo> activityStatisticsList(TbActivity tbActivity) {
        //只查询 进行中的活动 状态(已分配1  进行中2  回收3  伪线索4)
        tbActivity.setStatus("2");
        //获取 活动列表
        List<TbActivity> tbActivityList = tbActivityMapper.activityStatisticsList(tbActivity);
        List<ActivityStatisticsVo> returnList = new ArrayList<>();

        //遍历活动列表，针对每个活动进行统计操作
        for (TbActivity activity : tbActivityList) {

            //首先创建一个 ActivityStatisticsVo 对象，
            ActivityStatisticsVo asvo = new ActivityStatisticsVo();
            //并将当前活动的属性复制到该对象中
            BeanUtils.copyProperties(activity, asvo);

            //创建一个 TbClue 对象
            TbClue tbClue = new TbClue();
            //设置其属性值，包括活动ID、渠道和其他参数
            tbClue.setActivityId(activity.getId());
            tbClue.setChannel(activity.getChannel());
            tbClue.setParams(activity.getParams());

            //查询与当前活动相关的线索统计信息
            Map<String, Object> clueCount = tbClueMapper.countByActivity(tbClue);
            //设置线索数量、伪线索数量和转化为商机的数量
            if (clueCount != null) {
                if (clueCount.get("total") != null) {
                    asvo.setCluesNum(Integer.parseInt(clueCount.get("total").toString()));
                }
                if (clueCount.get("falseClues") != null) {
                    asvo.setFalseCluesNum(Integer.parseInt(clueCount.get("falseClues").toString()));
                }
                if (clueCount.get("toBusiness") != null) {
                    asvo.setBusinessNum(Integer.parseInt(clueCount.get("toBusiness").toString()));
                }
            }

            //创建一个 TbContract 对象
            TbContract tbContract = new TbContract();
            //设置其属性值，包括渠道、活动ID和其他参数
            tbContract.setChannel(activity.getChannel());
            tbContract.setActivityId(activity.getId());
            tbContract.setParams(activity.getParams());

            //查询与当前活动相关的合同统计信息
            Map<String, Object> contractCount = tbContractMapper.countByActivity(tbContract);

            //设置客户数量、交易金额和成本
            if (contractCount != null) {
                asvo.setCustomersNum(Integer.parseInt(contractCount.get("customersNum").toString()));
                if (contractCount.get("amount") == null) {
                    asvo.setAmount(0d);
                } else {
                    asvo.setAmount((Double) contractCount.get("amount"));
                }
                if (contractCount.get("cost") == null) {
                    asvo.setCost(0d);
                } else {
                    asvo.setCost((Double) contractCount.get("cost"));
                }

            }


            returnList.add(asvo);
        }
        return returnList;
    }

    /**
     * 线索统计明细列表 分页查询
     *
     * @param tbClue
     * @return
     */
    @Override
    public List<TbClue> cluesStatisticsList(TbClue tbClue) {
        return tbClueMapper.cluesStatisticsList(tbClue);
    }

    @Override
    public TableDataInfo<List<ReportSalesChannelStatisticsListDataVo>> channelStatisticsList(String beginCreateTime, String endCreateTime) {
        startPage();
        List<ReportSalesChannelStatisticsListDataVo> data = reportMapper.channelStatistics(beginCreateTime, endCreateTime);
        return getDataTable(data);
    }


    /**
     * 基础数据统计
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public IndexBaseInfoVO getBaseInfo(String beginCreateTime, String endCreateTime) {
        IndexBaseInfoVO indexBaseInfoVO = new IndexBaseInfoVO();
        //先获取到登录的用户名
        String userName = SecurityUtils.getUsername();
        //通过用户名获取用户信息
        SysUser user = userMapper.selectUserByUserName(userName);
        //获取对应数据
        Integer cluesNum = reportMapper.getClueNum(user.getUserId(), beginCreateTime, endCreateTime);
        Integer businessNum = reportMapper.getBusinessNum(user.getUserId(), beginCreateTime, endCreateTime);
        Integer contractNum = reportMapper.getContractNum(user.getUserName(), beginCreateTime, endCreateTime);
        Double salesAmount = reportMapper.getSalesAmount(user.getUserName(), beginCreateTime, endCreateTime);
        //封装对应数据
        indexBaseInfoVO.setCluesNum(cluesNum);
        indexBaseInfoVO.setBusinessNum(businessNum);
        indexBaseInfoVO.setContractNum(contractNum);
        indexBaseInfoVO.setSalesAmount(salesAmount);
        //返回结果
        return indexBaseInfoVO;
    }

    /**
     * 获取今日简报数据
     *
     * @return
     */
    @Override
    public IndexTodayInfoVO getTodayInfo() {
        IndexTodayInfoVO indexTodayInfoVO = new IndexTodayInfoVO();
        //先获取到登录的用户名
        String userName = SecurityUtils.getUsername();
        //通过用户名获取用户信息
        SysUser user = userMapper.selectUserByUserName(userName);

        Integer todayCluesNum = reportMapper.getTodayClueNum(user.getUserId());
        Integer todayBusinessNum = reportMapper.getTodayBusinessNum(user.getUserId());
        Integer todayContractNum = reportMapper.getTodayContractNum(user.getUserName());
        Double todaySalesAmount = reportMapper.getTodaySalesAmount(user.getUserName());
        //封装对应数据
        indexTodayInfoVO.setTodayCluesNum(todayCluesNum);
        indexTodayInfoVO.setTodayBusinessNum(todayBusinessNum);
        indexTodayInfoVO.setTodayContractNum(todayContractNum);
        indexTodayInfoVO.setTodaySalesAmount(todaySalesAmount);
        //返回结果
        return indexTodayInfoVO;
    }

    /**
     * 获取待办数据
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public IndexTodoInfoVO getTodoInfo(String beginCreateTime, String endCreateTime) {
        IndexTodoInfoVO indexTodoInfoVO = new IndexTodoInfoVO();
        //先获取到登录的用户名
        String userName = SecurityUtils.getUsername();
        //通过用户名获取用户信息
        SysUser user = userMapper.selectUserByUserName(userName);
//        Integer toallocatedCluesNum = reportMapper.getToallocatedCluesNum(user.getUserId(), beginCreateTime, endCreateTime);
//        Integer toallocatedBusinessNum = reportMapper.getToallocatedBusinessNum(user.getUserId(), beginCreateTime, endCreateTime);
        Integer tofollowedCluesNum = reportMapper.getTofollowedCluesNum(user.getUserId(), beginCreateTime, endCreateTime);
        Integer tofollowedBusinessNum = reportMapper.getTofollowedBusinessNum(user.getUserId(), beginCreateTime, endCreateTime);

        return indexTodoInfoVO;
    }

    /**
     * 线索转换龙虎榜
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public List<TigerDragonDTO> salesStatistic(String beginCreateTime, String endCreateTime) {
        List<TigerDragonDTO> tigerDragonDTOList = new ArrayList<>();
        List<SysUser> userList = userMapper.selectUserList(new SysUser());
        for (SysUser user : userList) {
            SysDept dept = deptMapper.selectById(user.getDeptId());

            TigerDragonDTO tigerDragonDTO = new TigerDragonDTO();
            Integer changeCluesNum = reportMapper.getChangeCluesNum(user.getUserId(), beginCreateTime, endCreateTime);
            Integer cluesNum = reportMapper.getClueNum(user.getUserId(), beginCreateTime, endCreateTime);
            Double radio = 0.0;

            if (cluesNum != 0) {
                radio = (double) (changeCluesNum / cluesNum);
            }


            tigerDragonDTO.setNum(changeCluesNum);
            tigerDragonDTO.setDeptName(dept.getDeptName());
            tigerDragonDTO.setCreateBy(user.getUserName());
            tigerDragonDTO.setRadio(radio);

            tigerDragonDTOList.add(tigerDragonDTO);
        }
        return tigerDragonDTOList;
    }


    /**
     * 商机转换龙虎榜
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public List<TigerDragonDTO> businessChangeStatistics(String beginCreateTime, String endCreateTime) {
        List<TigerDragonDTO> tigerDragonDTOList = new ArrayList<>();
        List<SysUser> userList = userMapper.selectUserList(new SysUser());
        for (SysUser user : userList) {
            TigerDragonDTO tigerDragonDTO = new TigerDragonDTO();
            SysDept dept = deptMapper.selectById(user.getDeptId());
            String deptName = dept.getDeptName();
            Integer changeBusinessNum = reportMapper.getChangeBusinessNum(user.getUserId(), beginCreateTime, endCreateTime);
            Integer BusinessNum = reportMapper.getBusinessNum(user.getUserId(), beginCreateTime, endCreateTime);
            Double radio = 0.0;

            if (BusinessNum != 0) {
                radio = (double) (changeBusinessNum / BusinessNum);
            }

            tigerDragonDTO.setNum(changeBusinessNum);
            tigerDragonDTO.setDeptName(dept.getDeptName());
            tigerDragonDTO.setCreateBy(user.getUserName());
            tigerDragonDTO.setRadio(radio);

            tigerDragonDTOList.add(tigerDragonDTO);

        }

        return tigerDragonDTOList;
    }
}
